import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo_2025_1/entity/my_location.dart';
import 'package:flutter_demo_2025_1/pages/share_info.dart';
import 'package:flutter_demo_2025_1/pages/share_location.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:getwidget/getwidget.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<MyLocation>? locationList;
  String? testStr;

  @override
  void initState() {
    super.initState();
    _getLocationList();
  }

  Future<void> _getLocationList() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    LocationList listWrapper = await LocationList.fromStorage(prefs);

    setState(() {
      locationList = listWrapper.list;
      testStr = prefs.getString('location_list');
    });
  }

  Future<void> _openShareLocation() async {
    final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => const ShareLocation()));
    if (result != null) {
      _getLocationList();
    }
  }

  Widget _itemBuilder(BuildContext context, int index) {
    MyLocation location = locationList![index];
    return GFListTile(
      color: Color(0xFFf5f5f5),
      margin: EdgeInsets.symmetric(vertical: 6.h, horizontal: 12.w),
      titleText: location.title,
      // title: Row(
      //   crossAxisAlignment: CrossAxisAlignment.start,
      //   children: [
      //     Expanded(child: Text(location.title, style: TextStyle(fontSize: 20.w))),
      //     IconButton(onPressed: () {}, icon: Icon(Icons.close))
      //   ],
      // ),
      subTitleText: location.desc,
      shadow: BoxShadow(color: Colors.black12, offset: Offset(0, 3.w)),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ShareInfo(location: location))
        );
      },
      avatar: (location.image != null && location.image != '') ? Image.file(
        File(location.image!),
        width: 80.w,
        height: 80.w,
        fit: BoxFit.cover,
      ) : Container(width: 80.w,height: 80.w, color: Color(0xFFe6f7ff)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF003a8c),
        foregroundColor: Colors.white,
        title: Text(widget.title),
      ),
      body: SafeArea(
        child: ListView.builder(
          itemCount: locationList?.length,
          itemBuilder: _itemBuilder,
        )
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _openShareLocation,
        tooltip: '分享新地点',
        child: const Icon(Icons.add_a_photo),
      ),
    );
  }
}